#!/usr/bin/env python3
"""1688商品搜索爬虫命令行入口"""

import argparse
import sys
import os
from datetime import datetime
from pathlib import Path

from rich.console import Console
from rich.table import Table
from rich.progress import Progress, SpinnerColumn, TextColumn
from rich.panel import Panel
from rich.text import Text

from crawler.spider import PlaywrightSpider
from crawler.enhanced_spider import EnhancedSpider
from crawler.utils import save_to_json, save_to_csv, print_product_summary
from config.settings import Settings


def create_parser() -> argparse.ArgumentParser:
    """创建命令行参数解析器"""
    parser = argparse.ArgumentParser(
        description="多平台商品搜索爬虫",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例用法:
  python main.py --keyword "手机壳" --pages 3
  python main.py --keyword "数据线" --platform taobao --pages 5 --output results.json
  python main.py --keyword "充电器" --platform jd --no-guangzhou --no-sort
        """
    )
    
    parser.add_argument(
        "--keyword", "-k",
        required=True,
        help="搜索关键词"
    )
    
    parser.add_argument(
        "--platform", "-pf",
        choices=["1688", "taobao", "jd"],
        default="taobao",
        help="选择平台 (默认: taobao)"
    )
    
    parser.add_argument(
        "--pages", "-p",
        type=int,
        default=Settings.MAX_PAGES,
        help=f"爬取页数 (默认: {Settings.MAX_PAGES})"
    )
    
    parser.add_argument(
        "--output", "-o",
        help="输出文件名 (支持 .json 和 .csv 格式)"
    )
    
    parser.add_argument(
        "--format", "-f",
        choices=["json", "csv", "both"],
        default="json",
        help="输出格式 (默认: json)"
    )
    
    parser.add_argument(
        "--no-guangzhou",
        action="store_true",
        help="不筛选广州发货的商品"
    )
    
    parser.add_argument(
        "--no-sort",
        action="store_true",
        help="不按销量排序"
    )
    
    parser.add_argument(
        "--headless",
        action="store_true",
        default=True,
        help="使用无头浏览器模式 (默认开启)"
    )
    
    parser.add_argument(
        "--show-browser",
        action="store_true",
        help="显示浏览器窗口 (调试用)"
    )
    
    parser.add_argument(
        "--enhanced",
        action="store_true",
        help="使用增强版爬虫 (更好的登录处理)"
    )
    
    parser.add_argument(
        "--verbose", "-v",
        action="store_true",
        help="显示详细日志"
    )
    
    return parser


def setup_output_dir() -> Path:
    """设置输出目录"""
    output_dir = Path(Settings.OUTPUT_DIR)
    output_dir.mkdir(exist_ok=True)
    return output_dir


def generate_filename(keyword: str, format_type: str) -> str:
    """生成输出文件名"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    safe_keyword = "".join(c for c in keyword if c.isalnum() or c in (' ', '-', '_')).strip()
    safe_keyword = safe_keyword.replace(' ', '_')
    return f"1688_{safe_keyword}_{timestamp}.{format_type}"


def display_results_table(products, console):
    """显示结果表格"""
    if not products:
        console.print("[red]没有找到符合条件的商品[/red]")
        return
    
    table = Table(title="搜索结果", show_header=True, header_style="bold magenta")
    table.add_column("序号", style="dim", width=4)
    table.add_column("商品名称", style="cyan", width=40)
    table.add_column("价格", style="green", width=10)
    table.add_column("销量", style="yellow", width=10)
    table.add_column("发货地", style="blue", width=10)
    table.add_column("供应商", style="magenta", width=20)
    
    # 只显示前20个结果
    display_count = min(20, len(products))
    
    for i, product in enumerate(products[:display_count], 1):
        title = product.title[:35] + "..." if len(product.title) > 35 else product.title
        supplier = product.supplier[:15] + "..." if len(product.supplier) > 15 else product.supplier
        
        table.add_row(
            str(i),
            title,
            product.price,
            product.sales,
            product.location,
            supplier
        )
    
    console.print(table)
    
    if len(products) > display_count:
        console.print(f"\n[dim]... 还有 {len(products) - display_count} 个商品未显示[/dim]")


def main():
    """主函数"""
    parser = create_parser()
    args = parser.parse_args()
    
    console = Console()
    
    # 获取平台信息
    from config.settings import Settings
    platform_info = Settings.PLATFORMS.get(args.platform, Settings.PLATFORMS['taobao'])
    
    # 显示启动信息
    console.print(Panel.fit(
        "[bold blue]多平台商品搜索爬虫[/bold blue]\n"
        f"搜索平台: [green]{platform_info['name']}[/green]\n"
        f"搜索关键词: [green]{args.keyword}[/green]\n"
        f"爬取页数: [yellow]{args.pages}[/yellow]\n"
        f"筛选广州: [cyan]{'是' if not args.no_guangzhou else '否'}[/cyan]\n"
        f"按销量排序: [magenta]{'是' if not args.no_sort else '否'}[/magenta]",
        title="配置信息"
    ))
    
    # 设置输出目录
    output_dir = setup_output_dir()
    
    try:
        # 创建爬虫实例
        headless = args.headless and not args.show_browser
        
        # 选择爬虫类型
        if args.enhanced:
            spider_class = EnhancedSpider
            spider_kwargs = {
                "platform": args.platform,
                "headless": headless,
                "verbose": getattr(args, 'verbose', False)
            }
        else:
            spider_class = PlaywrightSpider
            spider_kwargs = {
                "platform": args.platform,
                "headless": headless
            }
        
        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            console=console
        ) as progress:
            
            task = progress.add_task("正在搜索商品...", total=None)
            
            with spider_class(**spider_kwargs) as spider:
                # 执行搜索
                result = spider.search_products_sync(
                    keyword=args.keyword,
                    max_pages=args.pages,
                    sort_by_sales=not args.no_sort,
                    filter_guangzhou=not args.no_guangzhou
                )
            
            progress.update(task, description="搜索完成")
        
        # 显示结果
        console.print(f"\n[bold green]搜索完成！[/bold green]")
        console.print(f"找到 [bold yellow]{result.total_count}[/bold yellow] 个商品")
        
        if result.products:
            # 显示结果表格
            display_results_table(result.products, console)
            
            # 保存结果
            if args.output:
                output_file = output_dir / args.output
            else:
                if args.format == "json":
                    output_file = output_dir / generate_filename(args.keyword, "json")
                elif args.format == "csv":
                    output_file = output_dir / generate_filename(args.keyword, "csv")
                else:  # both
                    output_file = None
            
            # 保存文件
            if args.format == "json" or args.format == "both":
                if output_file and output_file.suffix == ".json":
                    json_file = output_file
                else:
                    json_file = output_dir / generate_filename(args.keyword, "json")
                save_to_json(result, str(json_file))
                console.print(f"[green]JSON文件已保存: {json_file}[/green]")
            
            if args.format == "csv" or args.format == "both":
                if output_file and output_file.suffix == ".csv":
                    csv_file = output_file
                else:
                    csv_file = output_dir / generate_filename(args.keyword, "csv")
                save_to_csv(result.products, str(csv_file))
                console.print(f"[green]CSV文件已保存: {csv_file}[/green]")
        
        else:
            console.print("[red]没有找到符合条件的商品[/red]")
    
    except KeyboardInterrupt:
        console.print("\n[yellow]用户中断操作[/yellow]")
        sys.exit(1)
    
    except Exception as e:
        console.print(f"[red]程序执行出错: {e}[/red]")
        if args.verbose:
            console.print_exception()
        sys.exit(1)


if __name__ == "__main__":
    main()